﻿var express = require('express');
var app = express();
var http = require('http').Server(app);
var net = require('net');
var url = require('url');
var child_process = require('child_process');


var process_child = child_process.fork(__dirname+'/child.js');
process_child.on('message', function (m) {
    console.log('PARENT got message:', m);
});
//聚合所有客户端  
var sockets = [];
var data_head_len = 16; //16字节包含crc和头部长度
function ProcessTcpServer(callback) {
    var server = net.createServer();
    //接受新的客户端连接  
    server.on('connection', function (socket) {
        var config_read_sensor = {};
        var port = socket.remotePort;
        var addr = socket.remoteAddress;
        console.log('CONNECTED: ' + socket.remoteAddress + ':' + socket.remotePort);
        sockets.push(socket);
        //缓冲区 512字节
        const buf = Buffer.allocUnsafe(512);
        //缓存中的数据长度
        var buf_datasize = 0;
        //69 00 01 00 01 04 08 46 7A 0B E8 41 F1 00 00 B2 87 16      // 压力16000  +  温度30.1 
      

        function process_packet_print(buff, pos,len) {
            //const buftemp = Buffer.from(buff, pos, len);
            const buftemp = Buffer.allocUnsafe(len);
            buff.copy(buftemp, 0, pos, pos+len);
            console.log(buftemp.toString('hex'));
        }
        function process_packet_1(buff,startpos,len) {
            var b_len = len - 2;//减去2个字节的crc校验长度
            const buftemp = Buffer.allocUnsafe(b_len);

            buff.copy(buftemp, 0, startpos, startpos + b_len);
            //console.log(buftemp.toString('hex'));
            process_child.send({ buffer: buftemp });
            //process_child.send("socket", socket);

        }

        function process_packet_compelete(buff) {
          //  console.log("process_packet_compelete %d", buf_datasize);
            var startpos = 0;
            var packet_len = 0;
            //var packet_len =  7 + 3 + buff[6+startpos];
            while (true) {
                if (buf_datasize >= 16) {
                    //读取包头两个字节长度
                    packet_len = buff.readInt16BE(0);
                   // console.log("packet_len %d", packet_len);
                }
                else {
                    //console.log("buf_datasize<7");
                    if(buf_datasize == 0)
                        return 0;
                    return startpos;
                }
                if (buf_datasize >= packet_len) {
                    //console.log("now buf_datasize %d packet_len %d startpos %d", buf_datasize, packet_len,startpos);
                    process_packet_1(buff, startpos, packet_len);
                    buf_datasize -= packet_len;
                    startpos += packet_len;

                }
                else {
                    if (buf_datasize == 0)
                        return 0;
                    return startpos;
                }
            }
        }

        socket.on('data', function (data) {
            //把数据拷贝到buf之后
            //nodejs.org doc : buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])
            data.copy(buf, buf_datasize);
            buf_datasize += data.length;
            //  console.log("now recv length " + buf_datasize);
            if (buf_datasize < 16) {//不够包头的长度，继续接收
                return;
            }
            var startpos = process_packet_compelete(buf);
            if (startpos > 0) {
                buf.copy(buf, 0, startpos, startpos + buf_datasize);
            }

        });
        //删除被关闭的连接  
        socket.on('close', function () {
            console.log('connection closed');
            var index = sockets.indexOf(socket);
            sockets.splice(index, 1);
        });
        socket.on('error', function (err) {
            // console.log("err");
        });
    });

    server.on('close', function () {
        console.log('Server closed');
    });

    server.listen(8052);
    console.log('listening on *:8052 tcpserver');
}

ProcessTcpServer(null);
//exports.ProcessTcpServer = ProcessTcpServer;